package bainuo

import com.alibaba.fastjson.JSON

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

def execute() {
    def conn
    def conn2
    try {
        // 初始化数据库连接
        conn2 = groovy.sql.Sql.newInstance(mypara.hqcon(1))
        conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))

        // 获取当前日期时间并格式化
        def now = LocalDateTime.now()
        def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        def formattedDateTime = now.format(formatter)
        def selectSql = "select * from WMS_time where type = '货位' "
        def NOWtime = conn2.firstRow(selectSql)


        def sql ="select pk_rack ,pk_stordoc,code ,name ,pk_psndoc ,memo,creationtime,modifiedtime from bd_rack where dr=0 and isnull(modifiedtime,creationtime) > ? and isnull(modifiedtime,creationtime) <= ?"
        def ckList= conn.rows(sql,[NOWtime.updateTime,formattedDateTime])

        processDataInBatches(ckList, 500,conn);

        // 插入时间记录
        def sqlTime = "UPDATE WMS_time set updateTime = ? where type = ?"
        conn2.execute(sqlTime, [ formattedDateTime,'货位'])
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.close()
        }
        if (conn2 != null) {
            conn2.close()
        }
    }
}
// 按批次处理数据
def processDataInBatches(def data, int batchSize,def conn) {
    for (int i = 0; i < data.size(); i += batchSize) {
        // 获取当前批次的子列表
        List<String> batch = data.subList(i, Math.min(i + batchSize, data.size()));
        // 调用处理方法
        processBatch(batch,conn);
    }
}
def processBatch(def ckList,def conn){
    List<Map<String,String>> items = new ArrayList<>();;
    //def select = conn.firstRow(sql)

    // 组装json
    for (def ckitem: ckList) {
        if (ckitem!= null){
            Map<String,String> item = new HashMap<>();
            def hwsql='select * from bd_rack where pk_parent = ?'
            def hwit = conn.firstRow(hwsql,[ckitem.pk_rack])
            if(hwit !=null){
                item.put("flvlflag",0);
            }else {
                item.put("flvlflag",1);
            }

            item.put("id",ckitem.pk_rack);
            item.put("wareHouseNo",ckitem.code);
            item.put("wareHouseName",ckitem.name);
            if (ckitem.pk_stordoc != null) {
                def sql2 = "SELECT pk_stordoc, name FROM bd_stordoc WHERE pk_stordoc = ?"
                def qitems = conn.rows(sql2, [ckitem.pk_stordoc]) // 使用参数化查询
                if (!qitems.isEmpty()) {
                    def det = qitems.first() // 假设我们只关心第一个匹配项，或者根据需要进行处理
                    item.put("parentNo", det.pk_stordoc)
                    item.put("parentName", det.name)
                }
            }
            item.put("storeKeeperName",ckitem.pk_psndoc);
            item.put("remark",ckitem.memo);
            item.put("creationtime",ckitem.creationtime);
            item.put("modifiedtime",ckitem.modifiedtime);
            items.add(item );
        }
    }

    Map<String,List> pushData = new HashMap<>()
    pushData.put("items",items);
    push(pushData)
}

def push(item){
    HQMHttpUtil.httpFWToMap("http://10.1.1.226:8099/wsdsjmcloud-v12/wbs/funcexe3/WMS_huowei001", item)
}
class HQMHttpUtil {
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public HQMHttpUtil() {
    }

    public HQMHttpUtil(HashMap<String, Object> account) {
        this.account = account;
    }
    public static Map httpFWToMap(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
//        DataOutputStream out
        OutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");

            conn.connect();

            out = conn.getOutputStream();
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            println("调用WMS返回报文="+result)
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
}